package cn.com.taiji.oospub.wechat.controller.servlet;

import cn.com.taiji.oospub.wechat.common.ObjectToXML;
import cn.com.taiji.oospub.wechat.common.OrderSend;
import cn.com.taiji.oospub.wechat.common.tool.SmallTicketPrinter;
import cn.com.taiji.oospub.wechat.common.util.HttpUtil;
import cn.com.taiji.oospub.wechat.common.wxpay.pay.XMLParser;
import cn.com.taiji.oospub.wechat.entity.CoursesOrders;
import cn.com.taiji.oospub.wechat.entity.CoursesOrdersDetails;
import cn.com.taiji.oospub.wechat.entity.MemberBaseInfo;
import cn.com.taiji.oospub.wechat.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.dreamyoung.mprelation.AutoMapper;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import static cn.com.taiji.oospub.wechat.common.Finals.PROPERTIES_PATH;

@WebServlet("/weixin/notity")
public class WeiXinNotify extends HttpServlet {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    private ICoursesOrdersService coursesOrdersManager;
    private ICoursesOrdersDetailsService coursesOrdersDetailsManager;
    private IMemberBaseInfoService memberBaseInfoManager;
    private IAccesstokensaveService accesstokensaveService;
    private IRestaurantService restaurantService;
    private OrderSend orderSend;
    private static InputStream kongxc_orderSend_musicStream;
    private Properties props = new Properties();
    private SmallTicketPrinter smallTicketPrinter;
    private AutoMapper autoMapper;
    public String PROPASS;
    public String PROJECT_CODE;
    public String CUS_NAME;

    @Override
    public void init() throws ServletException {
        super.init();
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        coursesOrdersManager = wac.getBean(ICoursesOrdersService.class);
        coursesOrdersDetailsManager = wac.getBean(ICoursesOrdersDetailsService.class);
        memberBaseInfoManager = wac.getBean(IMemberBaseInfoService.class);
        smallTicketPrinter = wac.getBean(SmallTicketPrinter.class);
        accesstokensaveService = wac.getBean(IAccesstokensaveService.class);
        restaurantService = wac.getBean(IRestaurantService.class);
        autoMapper = wac.getBean(AutoMapper.class);
        orderSend = wac.getBean(OrderSend.class);
        try {
            kongxc_orderSend_musicStream = wac.getResource(PROPERTIES_PATH).getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        doPost(req, resp);
    }

    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(), StandardCharsets.UTF_8));
        String line = "";
        StringBuffer buffer = new StringBuffer(1024);
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }
        String reXml = URLDecoder.decode(buffer.toString(), "utf-8");
        Map<String, Object> map = XMLParser.getMapFromXML(reXml);
        String return_code = (String) map.get("return_code");
        if ("SUCCESS".equalsIgnoreCase(return_code)) {
            System.out.println("wx支付回调开始============" + LocalDateTime.now());
            String out_trade_no = (String) map.get("out_trade_no");
            System.out.println("out_trade_no======================" + out_trade_no);
            CoursesOrders orders = coursesOrdersManager.findByProperty("order_code", out_trade_no);
            if (orders != null && orders.getStatus().equals(CoursesOrders.CoursesOrderStatus.WZF)) {
                orders = autoMapper.mapperEntity(orders);
                orders.setIdDelete("0");
                orders.setPayTime(LocalDateTime.now());
                orders.setStatus(CoursesOrders.CoursesOrderStatus.YZF);
                if ("3".equals(orders.getTakeMealType())) {
                    orders.setPayMemberName(orders.getAddress().getName());
                    orders.setMobile(orders.getAddress().getTel());
                }
                QueryWrapper<CoursesOrdersDetails> detailModel = new QueryWrapper<>();
                detailModel.eq("order_id", orders.getId());
                detailModel.eq("is_effective", true);
                detailModel.eq("creator", orders.getMemberId());
                List<CoursesOrdersDetails> detailList = coursesOrdersDetailsManager.queryList(detailModel);
                System.out.println("detailList============" + detailList);
//                for (CoursesOrdersDetails cod : detailList) {
//                    System.out.println("courseID===============" + cod.getCourseId());
//                    cod.setIsEffective(true);
//                }
                coursesOrdersManager.updateStatus(orders);
//                coursesOrdersDetailsManager.updateBatchById(detailList);
                //小票打印
//                smallTicketPrinter.printOrder(detailList, orders);
//                //微信消息推送
                String url = props.getProperty("kongxc_wx_diancan_orderServlet");
                url += "?orderId=" + orders.getId();
                String accessToken = accesstokensaveService.query().one().getAccessToken();
                orderSend.sendMet(accessToken, detailList.get(0).getCreatorInfo(), orders.getOrderCode(), url);
                props.load(kongxc_orderSend_musicStream);
                //-----订单详情推送开始----------
                MemberBaseInfo memberBaseInfo = memberBaseInfoManager.findById(orders.getMemberId());
                memberBaseInfo.setRestaurant(restaurantService.query().list().get(0));
                String kongxc_pos_http_server_url = props.getProperty("kongxc_pos_http_server_url");

                System.out.println("kongxc_pos_http_server_urlkongxc_pos_http_server_urlkongxc_pos_http_server_urlkongxc_pos_http_server_url");
                PROPASS = props.getProperty("PROPASS");
                CUS_NAME = props.getProperty("CUS_NAME");
                HttpUtil send = new HttpUtil(kongxc_pos_http_server_url);
                ObjectToXML toXml = new ObjectToXML();
                String resultXml = toXml.requestCPOrderInfoKongxc(PROPASS, CUS_NAME, memberBaseInfo.getSchool().getCode(), memberBaseInfo, orders, detailList, "0", "00", "微信");
                System.out.println(resultXml);
                send.sendToBoss(resultXml);
                //-------给pos 推送 订单数据结束-------
                System.out.println("wx支付回调结束");
                resp.getWriter().print("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
            }
        }
    }

    @Override
    public void destroy() {
        super.destroy();
    }
}
